package cn.sc.jedis;

import cn.sc.jedis.config.RedisInfo;
import cn.sc.jedis.serialization.DefaultSerialization;
import cn.sc.jedis.serialization.Serialization;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName JedisClusterFactory
 * @Author 谢卓才
 * @Description 创建redis集群的操作
 * @Date 2022/11/13 9:17
 */
public class JedisClusterFactory implements JedisFactory{

    private Serialization serialization;

    private static JedisClusterPool jedisClusterPool;

    public JedisClusterFactory(){
        this(new DefaultSerialization());
    }

    public JedisClusterFactory(Serialization serialization){
        this.serialization = serialization;
        if (serialization == null){
            this.serialization = new DefaultSerialization();
        }
    }


    @Override
    public JedisCluster create(RedisInfo redisInfo){
        try {
            String nodesStr = redisInfo.getCluster().getNodes();
            if(!StringUtils.hasLength(nodesStr)){
                return null;
            }
            Set<HostAndPort> nodes = new HashSet<>();
            for (String nodeStr : nodesStr.split(",")) {
                if(!StringUtils.hasLength(nodeStr)){
                    return null;
                }
                String nodeHostPost = nodeStr.trim();
                String[] nodeHostPostSplit = nodeHostPost.split(":");
                if(nodeHostPostSplit.length != 2){
                    return null;
                }
                nodes.add(new HostAndPort(nodeHostPostSplit[0],Integer.parseInt(nodeHostPostSplit[1])));
            }
            if(!nodes.isEmpty()){
                if(jedisClusterPool == null){
                    synchronized (JedisClusterFactory.class){
                        if(jedisClusterPool == null){
                            if(StringUtils.hasLength(redisInfo.getPassword())){
                                jedisClusterPool = new JedisClusterPool(nodes,redisInfo.getPassword());
                            } else {
                                jedisClusterPool = new JedisClusterPool(nodes);
                            }
                        }
                    }
                }
            }
            if(jedisClusterPool != null){
                return new JedisCluster(jedisClusterPool, serialization);
            }
            return null;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
